package co.yixiang.modules.user.service.impl;

import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.domain.PageResult;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.ShopCommonEnum;
import co.yixiang.exception.BadRequestException;
import co.yixiang.modules.user.domain.MonthlyManagementAwardDetail;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.MonthlyManagementAwardDetailService;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.dto.MonthlyManagementAwardDetailDto;
import co.yixiang.modules.user.service.dto.MonthlyManagementAwardDetailQueryCriteria;
import co.yixiang.modules.user.service.mapper.MonthlyManagementAwardDetailMapper;
import co.yixiang.modules.user.vo.MonthlyAwardDetailVo;
import co.yixiang.modules.user.vo.MonthlyAwardVo;
import co.yixiang.utils.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author lsh
* @date 2021-05-12
*/
@Slf4j
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "MonthlyManagementAwardDetail")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MonthlyManagementAwardDetailServiceImpl extends BaseServiceImpl<MonthlyManagementAwardDetailMapper, MonthlyManagementAwardDetail> implements MonthlyManagementAwardDetailService {

    private final YxUserService yxUserService;
    private final YxUserBillService yxUserBillService;
    private final MonthlyManagementAwardDetailMapper MonthlyManagementAwardDetailMapper;
    private final IGenerator generator;

    @Override
    //@Cacheable
    public PageResult<MonthlyManagementAwardDetailDto> queryAll(MonthlyManagementAwardDetailQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<MonthlyManagementAwardDetail> page = new PageInfo<>(queryAll(criteria));
        return generator.convertPageInfo(page,MonthlyManagementAwardDetailDto.class);
    }


    @Override
    //@Cacheable
    public List<MonthlyManagementAwardDetail> queryAll(MonthlyManagementAwardDetailQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(MonthlyManagementAwardDetail.class, criteria));
    }

    @Override
    //@Cacheable
    public MonthlyAwardVo getAwardMain4monthList(int page, int limit, long uid, String month){
        Page<MonthlyManagementAwardDetail> pageModel = new Page<>(page, limit);
        //uid=666;
        MonthlyAwardVo vo =MonthlyManagementAwardDetailMapper.getAwardMain4monthList(pageModel,uid,month);
        List<MonthlyAwardDetailVo> billDTOList =new ArrayList<MonthlyAwardDetailVo>();
        billDTOList = MonthlyManagementAwardDetailMapper.getAwardBranch4monthList(pageModel,uid,month);
        if(vo ==null){
            vo =new MonthlyAwardVo();
            vo.setTotalSum(new BigDecimal((0)));
            vo.setReceivableSum(new BigDecimal((0)));
            vo.setReceiptsSum(new BigDecimal((0)));
        }
        if(billDTOList.size()>0){
            for(MonthlyAwardDetailVo detail :billDTOList){
                YxUser user =yxUserService.getById(detail.getUid());
                detail.setHeadimgurl(user.getAvatar());
                detail.setUserPhone(user.getPhone());
                detail.setNickname(user.getNickname());
                detail.setLevel(user.getLevel());
            }
        }
        vo.setDetailList(billDTOList);
        return vo;
    }


    @Override
    public void download(List<MonthlyManagementAwardDetailDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MonthlyManagementAwardDetailDto MonthlyManagementAwardDetail : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户手机号", MonthlyManagementAwardDetail.getUserPhone());
            map.put("上级", MonthlyManagementAwardDetail.getParentId());
            map.put(" enabled",  MonthlyManagementAwardDetail.getEnabled());
            map.put("创建日期", MonthlyManagementAwardDetail.getCreateTime());
            map.put(" updateTime",  MonthlyManagementAwardDetail.getUpdateTime());
            map.put(" isDel",  MonthlyManagementAwardDetail.getIsDel());
            map.put(" level",  MonthlyManagementAwardDetail.getLevel());
            map.put("月份", MonthlyManagementAwardDetail.getMonth());
            map.put("昵称", MonthlyManagementAwardDetail.getNickname());
            map.put("微信头像地址", MonthlyManagementAwardDetail.getHeadimgurl());
            map.put("团队总业绩", MonthlyManagementAwardDetail.getTotalSum());
            map.put("应收管理奖金额", MonthlyManagementAwardDetail.getReceivableSum());
            map.put("实收管理奖金额", MonthlyManagementAwardDetail.getReceiptsSum());
            map.put("上级手机号", MonthlyManagementAwardDetail.getParentUserPhone());
            map.put("上级微信昵称", MonthlyManagementAwardDetail.getParentNickname());
            map.put("上级微信头像地址", MonthlyManagementAwardDetail.getParentHeadimgurl());
            map.put("是否开启", MonthlyManagementAwardDetail.getIsOpen());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 更新审核状态
     * @param resources MonthlyManagementAwardDetail
     */
    @Override
    public void doApprove(MonthlyManagementAwardDetail resources){
        log.info("Status============"+resources.getStatus());
        MonthlyManagementAwardDetail MonthlyManagementAwardDetail = this.getById(resources.getId());
        if(!ShopCommonEnum.EXTRACT_0.getValue().equals(MonthlyManagementAwardDetail.getStatus())){
            throw new BadRequestException("该申请已经处理过啦！");
        }
        YxUser user =yxUserService.getById(resources.getUid());
        BigDecimal receiptsSum =new BigDecimal("0");
        if(resources.getReceiptsSum().compareTo(new BigDecimal("0")) ==1){
            receiptsSum =resources.getReceiptsSum();
            BigDecimal usertotalSum =user.getNowMoney().add(receiptsSum);
            yxUserService.incMoney(user.getUid(),receiptsSum);
            yxUserService.incBrokeragePrice(receiptsSum,user.getUid());
            yxUserBillService.income(user.getUid(),"14", BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_2.getValue(),receiptsSum.doubleValue(),usertotalSum.doubleValue(), "月管理奖","");
            System.out.println(user.getLevel() + "级用户" + user.getUid()
                    + "：《月管理奖》" + receiptsSum + "元");
            MonthlyManagementAwardDetail.setStatus(1);
            this.saveOrUpdate(MonthlyManagementAwardDetail);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式

        log.info("time2222============"+df.format(new Date()));
    }

    /**
     * 统计分销人员
     * @param month
     * @return map
     */
    @Override
    public List<HashMap<String,Object>> getMonthData(String month) {
        List<HashMap<String,Object>> result = MonthlyManagementAwardDetailMapper.getMonthData(month);
        return result;
    }
}
